<?php
declare(strict_types=1);

namespace App\Service;

use App\Model\Enum\MchRoleIsSuperEnum;
use App\Model\Enum\MchRoleStatusEnum;
use App\Utils\CustomUtils;
use Hyperf\Di\Annotation\Inject;
use App\Model\Dao\MchSysRoleDao;
use App\Exception\XZXValidationException;
use App\Constants\XZXResponseCode;
use App\Utils\ArrayUtils;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Coroutine;
use App\Utils\DateUtils;
use App\Model\Dao\MchSysAccessDao;


class MchSysRoleService
{
    /**
     * @Inject()
     * @var MchSysRoleDao
     */
    private $MchSysRoleDao;

    /**
     * @Inject()
     * @var MchSysAccessDao
     */
    private $MchSysAccessDao;

    public function get($param)
    {
        $result = $this->MchSysRoleDao->get($param['id']);
        if (!$result) {
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::DATA_NOT_FOUND));
        }
        if(isset($result['createTime'])){
            $result['createTime'] = DateUtils::getDateTime($result['createTime']);
        }

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),$result);
    }

    public function del($param)
    {
        $result = $this->MchSysRoleDao->get($param['id']);
        if (!$result) {
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::DATA_NOT_FOUND));
        }
        
        try {
            $result = $this->MchSysRoleDao->del($param['id'],false);
        } catch (\Throwable $th) {
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::DEL_FAIL));
        }
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),CustomUtils::xzxEmptyObject());
    }

    public function add($param)
    {
        $data = $param;
        $data['id'] = CustomUtils::createUUID();
        $data['createTime'] = time();
        unset($data['source']);

        try {
            $this->MchSysRoleDao->insert($data);
        } catch (\Throwable $th) {
            CustomUtils::xzxDebug($th);
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::ADD_FAIL));
        }
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $data['id']);
    }

    public function edit($param)
    {
        $info = $this->MchSysRoleDao->get($param['id']);
        if (!$info) {
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::DATA_NOT_FOUND));
        }

        $superRoleResult = $this->isSuperRole($param['id']);
        if(!$superRoleResult['code'] && $param['status'] != 1)
        {
            throw new XZXValidationException('不能禁用超级管理员角色');
        }


        $id = $param['id'];
        $data = array();
        // isset($param['name']) && $data['name'] = $param['name'];
        // isset($param['desciption']) && $data['desciption'] = $param['desciption'];

        foreach($param as $k => $v){
            if($k == "id"){
                continue;
            }            
            if(isset($v)){
                $data[$k] = $v;
            }
        }
        unset($data['source']);
        CustomUtils::xzxDebug($data);
        
        try {
            $this->MchSysRoleDao->update($id, $data);
        } catch (\Throwable $th) {
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::EDIT_FAIL));
        }
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),CustomUtils::xzxEmptyObject());
    }

    public function list(array $param)
    {

        $limit = $param['limit'];
        $page = $param['page'];        

        $total = $this->MchSysRoleDao->getCount($param);
        $list = $this->MchSysRoleDao->getList($param, $page, $limit);

        CustomUtils::xzxDebug($list);
        // foreach ($list as $k => $v) {
        //     CustomUtils::xzxDebug($v);
        //     if(isset($v['createTime'])){
        //         $v['createTime'] = DateUtils::getDateTime($v['createTime']);
        //     }
        //     $list[$k] = $v;
        // }

        foreach ($list as $k=>$v){
            $node_data = $this->MchSysAccessDao->getNodeListByRoleId($v['id']);
            // xeDebug($node_data);
            $tmp = array();
            foreach ($node_data as $vv)
            {
                $tmp[]['id'] = $vv['nodeId'];
            }
            $list[$k]['nodeIdList'] = $tmp;

            if(isset($v['createTime'])){
                $v['createTime'] = DateUtils::getDateTime($v['createTime']);
            }
            $v['strType'] = MchRoleIsSuperEnum::getLabel($v['type']);
            $v['strStatus'] = MchRoleStatusEnum::getLabel($v['status']);
            $list[$k] = $v;
        }

        $data = array(
            'total' => $total,
            'list' => $list
        );

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),$data);
    }    

    public function getOptions ($param) {

        $list = $this->MchSysRoleDao->getWhereList(['status' => 1,"mchId" => $param['mchId']]);
        $list = array_column($list, 'name', 'id');

        $options = ArrayUtils::ArrToOptions($list);

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),$options);
    }

    public function isSuperRole($roleId){

        //选超级管理员角色类型
        $result = $this->MchSysRoleDao->getWhere(["id" => $roleId, "type" => 1]);
        // CustomUtils::xzxDebug($result);
        if(!$result){             
            return CustomUtils::xeServiceReturnData(XZXResponseCode::FAILED_CODE,XZXResponseCode::getMessage(XZXResponseCode::FAILED_CODE),CustomUtils::xzxEmptyObject());
        }
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),CustomUtils::xzxEmptyObject());
    }


    public function setAccess ($param) {

        // 全删
    
        $count = $this->MchSysAccessDao->delWhere(['mchId' => $param['mchId'], 'roleId' => $param['id']]);
        // xeDebug($count);

        // 全增
        $infoList = [];
        foreach ($param['nodeIdList'] as $v) {
            array_push($infoList, [
                'id'         => CustomUtils::createUUID(),
                'mchId'      => $param['mchId'],
                'roleId'     => $param['id'],
                'nodeId'     => $v,
                'status'     => 1,
                'createTime' => time(),
            ]);
        }
        
        $this->MchSysAccessDao->add($infoList);

        $data = [
            'infoList' => $infoList,
            'count' => $count,
        ];

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),$data);
    }
}